package com.yq.master.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yq.core.base.service.BaseService;
import com.yq.core.constant.Constant;
import com.yq.core.entity.SysUserEntity;
import com.yq.core.service.SysUserService;
import com.yq.core.util.Page;
import com.yq.core.util.PropertiesUtil;
import com.yq.core.util.Result;
import com.yq.master.annotation.AzerothAutowired;
import com.yq.master.bean.WebUserBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * 信  息: [yinquan] [2017-03-04] [1.2];
 * 描  述: 信息状态返回类，同意使用此类返回数据
 */
@Controller
@RequestMapping(value = "/sys/user")
public class SysUerController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SysUerController.class);

    @AzerothAutowired
    public SysUserService sysUserService;

    protected BaseService getServcie() {
        return sysUserService;
    }

    protected String getJumpData() {
        return "";
    }

    /*****************************************************************************************/
    /** 添加人员初始化 **/
    @RequestMapping(value = "insert",params="_m=init")
    public String insertInit(Model model, ServletRequest request) {
        return "sys/user/sys-user-insert";
    }

    /** 添加人员 **/
    @RequestMapping(value = "insert",params="_m=exec")
    @ResponseBody
    public Object insertExec(Model model, ServletRequest request) {

        String account = sysUserService.findAccount();

        super.fieldMap.clear();
        super.fieldMap.put("useStatus", "1");// 0禁用，1启用
        super.fieldMap.put("password", PropertiesUtil.getProperties("PASSWORD"));
        super.fieldMap.put("account", account);
        return super.insertExec(model, request);
    }

    /*****************************************************************************************/
    /** 编辑人员初始化 **/
    @RequestMapping(value = "update",params="_m=init")
    public String updateInit(Model model, ServletRequest request) {
        String uid = request.getParameter("uid");
        if(StringUtils.isNotBlank(uid)) {
            // 编辑初始化页面
            SysUserEntity sysUserEntity = sysUserService.findUniqueById(uid);
            model.addAttribute("obj", sysUserEntity);
        }
        return "sys/user/sys-user-update";
    }

    /** 编辑人员 **/
    @RequestMapping(value = "update",params="_m=exec")
    @ResponseBody
    public Object updateExec(Model model, ServletRequest request) {
        //super.fieldMap.clear();
        return super.updateExec(model, request);
    }

    /*****************************************************************************************/
    /** 删除人员 **/
    @RequestMapping(value = "delete",params="_m=exec")
    @ResponseBody
    public Object deleteExec(Model model, ServletRequest request) {
        super.fieldMap.clear();
        super.fieldMap.put("deleteStatus", "1");
        return super.updateExec(model, request);
    }

    /*****************************************************************************************/
    /** 管理员管理搜索初始化 **/
    @RequestMapping(value = "searchAdmin",params="_m=init")
    public String searchAdminInit(Model model, ServletRequest request) {
        return "sys/user/sys-user-admin-search";
    }

    /*****************************************************************************************/
    /** 人员搜索初始化 **/
    @RequestMapping(value = "search",params="_m=init")
    public String searchInit(Model model, ServletRequest request) {
        return "sys/user/sys-user-search";
    }

    /** 人员搜索 **/
    @RequestMapping(value = "search",params="_m=load")
    @ResponseBody
    public Object searchLoad(Model model, ServletRequest request) {

        Map<String, Object> parameters = Maps.newHashMap();
        Page page = super.getPage(request);

        String phone = request.getParameter("phone");
        String realName = request.getParameter("realName");
        String account = request.getParameter("account");
        String name = request.getParameter("name");

        if(StringUtils.isNotBlank(phone)) { parameters.put("phone", phone); }
        if(StringUtils.isNotBlank(realName)) { parameters.put("realName", realName); }
        if(StringUtils.isNotBlank(account)) { parameters.put("account", account); }
        if(StringUtils.isNotBlank(name)) { parameters.put("name", name); }

        page = sysUserService.pageUserList(parameters, page);
        return page;
    }

    /*****************************************************************************************/
    /** 管理员授权初始化 **/
    @RequestMapping(value = "accredit",params="_m=init")
    public String accreditInit(Model model, ServletRequest request) {
        String uid = request.getParameter("uid");
        model.addAttribute("userUid", uid);
        return "sys/user/sys-user-admin-accredit";
    }

    /** 管理员授权 **/
    @RequestMapping(value = "accredit",params="_m=exec")
    @ResponseBody
    public Object accreditExec(Model model, ServletRequest request) {

        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);

        try{
            String userUid = request.getParameter("userUid");
            String roleUids = request.getParameter("roleUids");

            if(StringUtils.isBlank(userUid)) {
                result.resoutError("管理员标识不能为空");
                return result;
            }

            //WebUserBean webUserBean = super.getWebUserBean(request);

            parameters.put("roleUids", roleUids);
            parameters.put("userUid", userUid);

            sysUserService.updateAccredit(parameters);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }

    /** 管理员角色树 **/
    @RequestMapping(value = "accredit",params="_m=tree")
    @ResponseBody
    public Object accreditTree(Model model, ServletRequest request) {

        Map<String, Object> parameters = Maps.newHashMap();
        Map<String, Object> obj = Maps.newHashMap();
        List<Map<String, Object>> tree = Lists.newArrayList();

        parameters.put("userUid", request.getParameter("userUid"));
        List<Map<String, Object>> list = sysUserService.userRoleTree(parameters);

        for(Map<String, Object> m:list) {
            obj.put(m.get("id").toString(), m);
        }

        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            // 获得当前对象
            Map<String, Object> role = (Map<String, Object>) entry.getValue();

            // 是否选中
            if(role.get("ur")!=null){
                role.put("checked", true);
            }
            tree.add(role);

        }
        return tree;
    }

    /*****************************************************************************************/
    /** 启用 **/
    @RequestMapping(value = "on",params="_m=exec")
    @ResponseBody
    public Object onExec(Model model, ServletRequest request) {
        return lockUser(request, "1");
    }

    /** 禁用 **/
    @RequestMapping(value = "off",params="_m=exec")
    @ResponseBody
    public Object offExec(Model model, ServletRequest request) {
        return lockUser(request, "0");
    }

    /*****************************************************************************************/
    /** 启用、禁用管理员 **/
    private Object lockUser(ServletRequest request, String type) {
        Map<String, Object> parameters = Maps.newHashMap();
        Result result = isCheck(request);
        Date date = new Date();

        try {
            WebUserBean webUserBean = getWebUserBean(request);
            SysUserEntity sysUserEntity = sysUserService.findUniqueById(getUid(request));
            sysUserEntity.setUseStatus(type);
            sysUserEntity.setUpdateBy(webUserBean.getUid());
            sysUserEntity.setUpdateAt(date);

            sysUserService.update(sysUserEntity);

            result.resoutSucess("操作成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            result.resoutError("操作失败");
        }

        return result;
    }
}
